<!-- 导入证书信息 -->
<template>
  <el-dialog
    :title="dialogTitle"
    :visible="visible"
    width="600px"
    @close="handleClose"
  >
    <div style="padding: 20px">
      <!-- 证书信息模板 -->
      <el-form :model="form" label-width="120px" size="small">
        <el-form-item label="证书信息模板">
          <el-button type="primary" @click="downloadTemplate"
            >下载证书信息模板</el-button
          >
        </el-form-item>

        <!-- 上传证书信息 -->
        <el-form-item label="上传证书信息">
          <el-upload
            ref="upload"
            :action="uploadFileUrl"
            :auto-upload="false"
            :before-upload="handleBeforeUpload"
            :file-list="fileList"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :headers="headers"
            accept=".xlsx,.xls"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或点击上传</div>
            <div class="el-upload__tip" slot="tip">
              请上传大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>，
              格式为
              <b style="color: #f56c6c">{{ fileType.join("/") }}</b> 的文件
            </div>
          </el-upload>
        </el-form-item>

        <!-- 上传方式 -->
        <el-form-item label="上传方式">
          <el-radio-group v-model="uploadMode">
            <el-radio label="覆盖">覆盖</el-radio>
            <el-radio label="补充">补充</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirmImport" :loading="uploadLoading"
        >导 入</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  name: "ImportCertificateDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dialogTitle: "导入证书信息",
      form: {},
      uploadMode: "覆盖",
      fileList: [],
      uploadedFile: null,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传文件服务器地址
      fileType: ["xlsx", "xls"], // 允许上传的文件类型
      fileSize: 10, // 文件大小限制(MB)
      uploadLoading: false, // 上传加载状态
      number: 0, // 上传计数器
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  methods: {
    // 下载模板
    downloadTemplate() {
      // 实际的下载逻辑
      const baseUrl = process.env.VUE_APP_DOWNLOAD_BASE_URL;
      const filePath = "/statics/2025/10/30/Excel.xlsx";
      const fullUrl = `${baseUrl}${filePath}`;

      this.$download.saveAs(fullUrl, "证书信息模板.xlsx");
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split(".");
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(
            `文件格式不正确，请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件名是否包含特殊字符
      if (file.name.includes(",")) {
        this.$modal.msgError("文件名不正确，不能包含英文逗号!");
        return false;
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件改变事件
    handleChange(file, fileList) {
      this.fileList = fileList;
      this.uploadedFile = file.raw;
    },

    // 删除文件
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.uploadedFile = null;
    },

    // 上传成功处理
    handleUploadSuccess(res, file) {
      this.$modal.closeLoading();
      if (res.code === 200) {
        this.$message.success("导入成功");
        this.$emit("import-success", {
          file: this.uploadedFile,
          mode: this.uploadMode,
        });
        this.cancel();
      } else {
        this.$modal.msgError(res.msg || "导入失败");
      }
      this.uploadLoading = false;
    },

    // 上传失败处理
    handleUploadError(err) {
      this.$modal.closeLoading();
      this.$modal.msgError("上传文件失败，请重试");
      this.uploadLoading = false;
    },

    // 取消操作
    cancel() {
      this.$emit("update:visible", false);
      this.reset();
    },

    // 确认导入
    confirmImport() {
      if (!this.uploadedFile) {
        this.$message.warning("请先上传文件");
        return;
      }

      // 执行上传
      this.uploadLoading = true;
      this.$refs.upload.submit();
    },

    // 重置表单
    reset() {
      this.uploadMode = "覆盖";
      this.fileList = [];
      this.uploadedFile = null;
      this.uploadLoading = false;
    },
    handleClose() {
      this.$emit("update:visible", false);
    },
  },
};
</script>
